from typing import Any
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.v1.router import api_router
from app.core.config import settings


def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.app_name,
        version="0.1.0",
        description=(
            "CertDNSHub - 域名解析与证书自动化平台，"
            "示例项目用于演示多云 DNS/证书接口形态。"
        ),
        debug=settings.debug,
    )

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @app.get("/health", tags=["Health"])
    def health_check() -> dict[str, Any]:
        from app.services.datastore import store
        
        # Check ACME account (creates if missing)
        try:
            account = store.get_default_acme_account()
            acme_status = "ok" if account else "error"
        except Exception as e:
            acme_status = f"error: {str(e)}"
            
        return {
            "status": "ok", 
            "service": settings.app_name,
            "acme_account": acme_status
        }

    app.include_router(api_router, prefix=settings.api_prefix)
    return app


app = create_app()
